# -*- coding: UTF-8 -*-
"""
Course:        CS408 Computer Science Project B, TEAM 1
Semester:      2010 SPRING
Project:       DOHN(Web-based Account Book System)

File:          users.py
Description:   User package for mypageview, signupview, adminview
Class:         MypageView, MypageController, SignupView, SignupController, 
               AdminView, AdminController
"""


import sessions
import db
import views
import utils
import string
import re


class MypageView:
    """
    """
    def show_index_window(self, req):
        """
        @author: Sangyong Gil
        @summary: Index Window of My page
        @param req: Request 
        """
        return self.show_category_window(req)
    
    def show_userinfo_window(self, req):
        """
        @author: Kyeonghwan Jin
        """
        # Fetch
        user_id = sessions.get_id(req)
        # Fetch category_tb ----------------------------------------
        query = "SELECT user_mail FROM member_tb " + \
                "WHERE(user_id = '%s') LIMIT 1" % (user_id)
        data = db.run_query(query)
        
        in_src = str(data[0][0]).strip()
        
        # Get html content
        src_path = utils.get_abs_path() + "/html/mypage_user_info.html"
        src = utils.get_file_content(src_path)
        src = src.replace("<!---CONTENT!--->", in_src)
        return src
    
    def show_user_out_window(self, req):
        """
        @author: Sangyong Gil
        @summary: Before deleting user account, confirm the user whether he/she really wants membership termination
        """
        return utils.replace("mypage_user_out.html","")
    
    def show_category_window(self, req):
        """
        @author: Kyeonghwan Jin
        """
        
        # ----------------------------------------
        # Fetch
        user_id = sessions.get_id(req)
        # Fetch category_tb ----------------------------------------
        query = "SELECT num, description FROM category_tb " + \
                "WHERE(user_id = '%s') ORDER BY `order`" % (user_id)
        data = db.run_query(query)
    
        
        # ----------------------------------------
        # Reassemble items
        # @see: The reason why I don't use string concatenation
        #    but use list and join is speed enhancement.
        """
        <tr>
            <td>
            Meal
            </td>
            <td>
            <a href="#">Del</a>
            </td>
        </tr>
        """
        in_src = []
        for atuple in data:
            in_src.append("<tr><td>%s</td><td><a href=\"do_category_delete?num=%s\">Del</a></td></tr>" \
                           % ( str(utils.get_category_name(atuple[0])).strip(), str(atuple[0]).strip() ))
            # end a line
            
        in_src = ''.join(in_src)
        
    
        # ----------------------------------------
        # Get html content
        src_path = utils.get_abs_path() + "/html/mypage_category_edit.html"
        src = utils.get_file_content(src_path)
        src = src.replace("<!---CONTENT!--->", in_src)
        return src
        
        
    def show_category_add_window(self):
        """
        @author: Kyeonghwan Jin
        """
        src_path = utils.get_abs_path() + "/html/p_add_category.html"
        src = str(utils.get_file_content(src_path))
        return src
    
    def show_pattern_window(self, req):
        """
        @author: Sangyong Gil
        @param req: Request
        @return: HTML source of pattern list window 
        """
        
        # ----------------------------------------
        # Fetch
        session_id = sessions.get_id(req)
        query = "SELECT num, description FROM category_tb WHERE user_id = '%s' ORDER BY num" % (session_id)
        data = db.run_query(query)
        
        # ----------------------------------------
        # Reassemble items
        # @see: The reason why I don't use string concatenation
        #    but use list and join is speed enhancement.
        in_src = []
        
        for atuple in data:
            # start a line
            header = """<div id="category">
                            <div id="category_top">
                                <div id="category_name">%s
                                <input type="button" value="Add" onclick="open_window('pattern_add?cat=%d')" style="width:80px; height:27px; color:#fff; border:none; background: url(../html/images/button.jpg) ; margin-left: 590px; margin-top:-20px; ">
                                </div>
                            </div>
                            <div id="pattern_table">
                                <table id="basic" style="width:400px;">
                                <thead>
                                <tr><th scope="col" colspan=2>Description</th>
                                </tr>
                                </thead>""" % (string.strip(str(atuple[1])),int(atuple[0]))
            in_src.append(header)
            query = "SELECT description, num " + \
                "FROM pattern_tb " + \
                "WHERE(user_id = '%s' AND category = '%d' )"% (session_id, int(atuple[0]))
            pattern = db.run_query(query)
            
            for btuple in pattern:
                tmp = "<tr><td>%s</td>" % (str(btuple[0])) 
                in_src.append(tmp)
                in_src.append("<td id=\"modify\" style=\"width:20%; text-align:center;\">")
                tmp = "<a href=\"do_pattern_delete?pattern=%d \">Del</a></td></tr>\n" % (int(btuple[1]))
                in_src.append(tmp)
            
            in_src.append("</table></div></div>")
            # end a line
        in_src = ''.join(in_src)
        
        src = utils.replace("mypage_recog_pattern.html", in_src)
        return src
    
    def show_pattern_add_window(self, req, cat):
        """
        @author: Sangyong Gil
        @param req: Request
        @param cat: category number
        @return: HTML source of pattern add window
        """
        content = "<input type=\"hidden\" value=%d name=\"category\" style=\"\" />" % (int(cat)) 
        src = utils.replace("p_add_description.html", content)
        return src


class MypageController:
    """
    """
    def query_delete_userinfo(self, req, pw):
        """
        @author: Sangyong Gil
        @param req: Request
        @param pw: Password
        @summary: Cancel the user account
        """
        user_id = sessions.get_id(req)
        
        query = "SELECT password FROM member_tb WHERE user_id='%s'" % user_id
        data = db.run_query(query)
        list_str = list(data[0])
        password = ''.join(list_str)

        if password == pw:
            query = "DELETE FROM transaction_tb WHERE user_id = '%s'" % user_id
            db.execute_query(query)
            query = "DELETE FROM shortcut_tb WHERE user_id = '%s'" % user_id
            db.execute_query(query)
            query = "DELETE FROM pattern_tb WHERE user_id = '%s'" % user_id
            db.execute_query(query)
            query = "DELETE FROM category_tb WHERE user_id = '%s'" % user_id
            db.execute_query(query)
            query = "DELETE FROM member_tb WHERE user_id = '%s'" % user_id
            db.execute_query(query)
            utils.redirect(req, "sign_out")
        else:
            alert = "<script type=\"text/javascript\">alert('Password incorrect!');</script>" 
            src = utils.replace("mypage_user_out.html",alert)
            return src
    
    def query_add_category(self, req, category):
        """
        @author: Kyeonghwan Jin
        """
        user_id = sessions.get_id(req)

        query = "INSERT INTO category_tb (`num`, `user_id`, `description`, " + \
                "`order`) VALUES " + \
                "(NULL, '%s', '%s', '0')" \
                %(user_id, category)
        db.execute_query(query)
        return
    
    def query_delete_category(self, req, num):
        """
        @author: Kyeonghwan Jin
        """
        user_id = sessions.get_id(req)
        
        # Check permission
        query = "SELECT user_id FROM category_tb " + \
                "WHERE(num='%s')" % (num)
        data = db.run_query(query)
        if not data[0][0] == user_id:
            return "You don't have permission to edit this transaction."
        
        # past data
        query = "DELETE FROM category_tb WHERE(user_id='%s' " % (user_id) + \
                "AND num='%d') LIMIT 1" % (int(num))
        db.execute_query(query)
        return True
    
    def query_add_pattern(self, req, category, description_name):
        """
        @author: Sangyong Gil
        @param req: Request
        @param category: category number
        @param description_name: new description (pattern)
        """
        user_id = sessions.get_id(req)
        
        query = "INSERT INTO pattern_tb (user_id, category, description) VALUES ('%s', '%d', '%s')" % (user_id, int(category), description_name)
        db.execute_query(query)
        return
    
    def query_delete_pattern(self, req, pattern):
        """
        """
        user_id = sessions.get_id(req)
        
        query = "DELETE FROM pattern_tb WHERE (user_id = '%s' AND num = '%d') LIMIT 1" % (user_id, int(pattern))
        db.execute_query(query)
        utils.redirect(req, "pattern_list")


class SignupView:
    """
    @author: SungHyuk Im
    @return: signup page
    
    @attention: This class doesn't have argument, req
    """
    def show_index_window(self):
        """
        @author: SungHyuk Im
        @summary: Sign up index page.
        """
        return self.show_signup_window()
    
    def show_signup_window(self):
        """
        @author: SungHyuk Im
        @summary: Sign up page.
        """
        src_path = utils.get_abs_path() + "/html/signup.html"
        src = utils.get_file_content(src_path)
        return src
    
    def show_id_check_window(self, req, id):
        """
        @author: Sangyong Gil
        @param req: Request
        @param id: ID
        """
        sign_obj = SignupController()
        if sign_obj.check_id(id) == True:
            return utils.replace("id_check.html",id)
        else:
            return utils.replace("id_check_fail.html",id)

class SignupController:
    """
    @author: SungHyuk Im
    @summary: DB query manager for Sign up.
    """
    def query_add_userinfo(self, user_id, email, pw1, pw2):
        """
        @author: SungHyuk Im
        """
        # @@informaton
        # Columns of member_tb
        #: user_id  password  user_mail  is_admin  balance  last_transaction  
        if self.check_id(user_id) == False:
            return False
        else:        
            sql = "INSERT INTO member_tb " + \
                  "(user_id, password, user_mail, is_admin, balance, " + \
                  "last_login) " + \
                  " VALUES ('%s', '%s', '%s', '0', '0', NULL)" \
                  % (user_id, pw1, email)
            db.execute_query(sql)
            return True
    
    def query_edit_userinfo(self, req, email, pw):
        """
        @author: Kyeonghwan Jin
        """
        user_id = sessions.get_id(req)
        
        # transaction_tb
        query = "UPDATE member_tb SET " + \
                "user_mail = '%s'" % (str(email).strip()) + \
                ", password = '%s' " % (str(pw).strip()) + \
                "WHERE(user_id = '%s') LIMIT 1" % (user_id)
        db.execute_query(query)
        return True
    
    def check_id(self, user_id):
        """
        @author: Sangyong Gil
        @param user_id: Desiring user_id
        @return: True if available, False if unavailable 
        """
        query = "SELECT user_id FROM member_tb WHERE user_id = '%s'" % user_id
        data = db.run_query(query)
        if len(list(data)) == 0:
            return True
        else:
            return False

class AdminView:
    """
    """
    def show_index_window(self, req):
        """
        @author: Sangyong Gil
        @param req: Request
        """
        return self.show_manage_window(req)
    
    def show_manage_window(self, req):
        """
        @author: Sangyong Gil
        @param req: Request
        """
        
        # ----------------------------------------
        # Check admin
        session_id = sessions.get_id(req)
        query = "SELECT is_admin FROM member_tb WHERE user_id='%s'" % session_id
        data = db.run_query(query)
        list_str = list(data[0])
        is_admin = str(list_str)
        is_admin = is_admin.replace('[', "")
        is_admin = is_admin.replace(']', "")
        is_admin = is_admin.replace('.0', "")
        
        if int(is_admin) == 0:
            sessions.sign_out(req)
            return utils.get_html_with_msg( "main.html", \
                                       "Not an administrator! Check ID and sign-in again.")
        else:
            query = "SELECT user_id, user_mail, last_login FROM member_tb WHERE is_admin='0' ORDER BY user_id"
            data = db.run_query(query)

        
            # ----------------------------------------
            # Reassemble items
            # @see: The reason why I don't use string concatenation
            #    but use list and join is speed enhancement.
            in_src = []
            count = 0
            for atuple in data:
                if 0==count:
                    in_src.append("\t<tr><td>")                    
                    count = 1
                else:
                    in_src.append("\t<tr class=\"odd\"><td>")
                    count = 0
                
                in_src.append("%s</td>\n" % (string.strip(str(atuple[0]))))    
                in_src.append("\t<td>%s</td>\n" % (string.strip(str(atuple[1]))))
                in_src.append("\t<td>%s</td>\n" % (string.strip(str(atuple[2]))))
                in_src.append("\t<td><a href=\"confirm_user_delete?user=")
                in_src.append("%s\">Delete</a></td></tr>\n" % (string.strip(str(atuple[0]))))
                
            # end a line
            in_src = ''.join(in_src)
        
            result = utils.replace("admin.html", in_src)
            return result
    
    def show_user_delete_window(self, req, user):
        # ----------------------------------------
        # Check admin
        session_id = sessions.get_id(req)
        query = "SELECT is_admin FROM member_tb WHERE user_id='%s'" % session_id
        data = db.run_query(query)
        list_str = list(data[0])
        is_admin = str(list_str)
        is_admin = is_admin.replace('[', "")
        is_admin = is_admin.replace(']', "")
        is_admin = is_admin.replace('.0', "")
        
        if int(is_admin) == 0:
            return utils.get_html_with_msg( "main.html", \
                                        "Not an administrator! Check ID.")
        else:
            in_src = []
            tmp = """<script>if(confirm("Really want to delete the user account?")){ location.href=""" 
            in_src.append(tmp)
            in_src.append("\"do_user_delete?user=%s\"" % user)
            in_src.append("} else { location.href=\"admin\" }</script>")
            in_src = ''.join(in_src)            
            return in_src

class AdminController:
    """
    """
    def query_delete_user(self, req, user):
        """
        @author: Sangyong Gil
        @param req: Request
        @param user: A user targeted to be deleted
        """
        # ----------------------------------------
        # Check admin
        session_id = sessions.get_id(req)
        query = "SELECT is_admin FROM member_tb WHERE user_id='%s'" % session_id
        data = db.run_query(query)
        list_str = list(data[0])
        is_admin = str(list_str)
        is_admin = is_admin.replace('[', "")
        is_admin = is_admin.replace(']', "")
        is_admin = is_admin.replace('.0', "")
        
        if int(is_admin) == 0:
            return utils.get_html_with_msg( "main.html", \
                                        "Not an administrator! Check ID.")
        else:
            query = "DELETE FROM transaction_tb WHERE user_id = '%s'" % user
            db.execute_query(query)
            query = "DELETE FROM shortcut_tb WHERE user_id = '%s'" % user
            db.execute_query(query)
            query = "DELETE FROM pattern_tb WHERE user_id = '%s'" % user
            db.execute_query(query)
            query = "DELETE FROM category_tb WHERE user_id = '%s'" % user
            db.execute_query(query)
            query = "DELETE FROM member_tb WHERE user_id = '%s'" % user
            db.execute_query(query)
            utils.redirect(req, "admin")